package com.hgc.ch02.semaphore;

import java.sql.Connection;
import java.util.Random;

/**
 * Created by 01367627 on 2019/7/8.
 */
public class SemaphorePoolTest {
    private static DBPoolSemaphore pool = new DBPoolSemaphore(10);

    private static class MyRunnable implements Runnable {

        private Random r = new Random();

        @Override
        public void run() {
            long start = System.currentTimeMillis();
            try {
                Connection connection = pool.fetchConnecion();
                System.out.println(Thread.currentThread().getName() + "获取连接耗时：" + (System.currentTimeMillis() - start) + "ms");
                Thread.sleep(r.nextInt(200));
                System.out.println(Thread.currentThread().getName() + "运行完毕，归还连接！");
                pool.releaseConnection(connection);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Runnable r = new MyRunnable();
        for (int i = 0; i < 50; i++) {
            new Thread(r, "t" + i).start();
        }
    }
}
